package com.it.jzs.service.admin.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.it.jzs.dao.admin.AdminBlogMapper;
import com.it.jzs.dao.admin.AdminBlogTagsMapper;
import com.it.jzs.dao.admin.AdminTagMapper;
import com.it.jzs.dao.admin.AdminTypeMapper;
import com.it.jzs.pojo.Blog;
import com.it.jzs.pojo.BlogTags;
import com.it.jzs.service.admin.AdminBlogService;
import com.it.jzs.vo.AdminBlogVo;
import com.it.jzs.vo.EditBlogVo;
import com.it.jzs.vo.Result;
import com.it.jzs.vo.params.UpdateBlogParams;
import com.it.jzs.vo.params.WriteParams;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
@Slf4j
public class AdminBlogServiceImpl implements AdminBlogService {
    @Resource
    private AdminTagMapper tagMapper;
    @Resource
    private AdminTypeMapper typeMapper;
    @Resource
    private AdminBlogMapper blogMapper;


    @Resource
    private AdminBlogTagsMapper blogTagsMapper;

    @Override
    @Transactional
    public Result<Object> update(UpdateBlogParams updateBlogParams) {  // 修改博客
        String content = updateBlogParams.getContent();
        String description = updateBlogParams.getDescription();
        Integer id = updateBlogParams.getId();
        List<Integer> tagIds = updateBlogParams.getTagIds();
        String title = updateBlogParams.getTitle();
        Integer typeId = updateBlogParams.getTypeId();
        Integer userId = updateBlogParams.getUserId();
        if (StringUtils.isEmpty(content) ||
                StringUtils.isEmpty(description) ||
                StringUtils.isEmpty(id) ||
                StringUtils.isEmpty(tagIds) ||
                StringUtils.isEmpty(title) ||
                StringUtils.isEmpty(typeId)
        ) return Result.error(null, "修改博客数据不合法");
        Blog blog = new Blog();
        blog.setContent(content);
        blog.setFirstPicture(updateBlogParams.getFirstPicture()); // 首图的信息
        blog.setDescription(description);
        blog.setTitle(title);
        blog.setTypeId(typeId);
        blog.setId(id);
        blog.setUserId(userId);
        blog.setUpdateTime(System.currentTimeMillis());
        blogTagsMapper.delete(new QueryWrapper<BlogTags>().eq("blogs_id", id)); // 先删除中间表的数据 ，
        for (Integer tagId : tagIds) {  // 循环插入
            BlogTags blogTags = new BlogTags();
            blogTags.setTagsId(tagId);
            blogTags.setBlogsId(id);
            blogTagsMapper.insert(blogTags);
        }

        int i = blogMapper.updateById(blog);
        if (i > 0) {
            return Result.success(null, "博客修改成功！");
        }
        return Result.error(null, "博客修改失败");
    }

    @Override
    // 所以在进行博客相关的操作，要先对这3项进行非空的判断
    @Transactional
    public Result<Object> insert(WriteParams writeParams) {  // 插入一篇博客，博客和标签是一对多的关系  因为博客表和userid，分类id，标签id有关联
        Blog blog = new Blog();
        String content = writeParams.getContent();
        String title = writeParams.getTitle();
        Integer typeId = writeParams.getTypeId();
        List<Integer> tagIds = writeParams.getTagIds();
        Integer userId = writeParams.getUserId();
        String description = writeParams.getDescription();
        if (StringUtils.isEmpty(content) || StringUtils.isEmpty(title) || StringUtils.isEmpty(tagIds) || StringUtils.isEmpty(typeId) || StringUtils.isEmpty(userId)
                || StringUtils.isEmpty(description)
        ) {
            return Result.error(null, "数据不合法");
        }
        Long createTime = System.currentTimeMillis();
        blog.setFirstPicture(writeParams.getFirstPicture()); // 首图
        blog.setContent(writeParams.getContent());   // 内容
        blog.setDescription(writeParams.getDescription()); // 介绍
        blog.setUserId(writeParams.getUserId()); // 用户id
        blog.setTypeId(writeParams.getTypeId());  // 分类id
        blog.setCreateTime(createTime); // 创建时间
        blog.setUpdateTime(System.currentTimeMillis()); // 修改时间
        blog.setTitle(writeParams.getTitle()); // 标题
        blog.setViews(0);  // 初始为0观看数
//        int insert = blogMapper.insert(blog);
        int insert = blogMapper.insert(blog);
        Blog blog1 = blogMapper.selectOne(new QueryWrapper<Blog>().eq("user_id", userId).eq("create_time", createTime));
        Integer id = blog1.getId();  // 获取刚刚插入博客的id ，用于 维护博客标签表
//        blogTagsMapper.
        for (Integer tagId : tagIds) {
            BlogTags blogTags = new BlogTags();
            blogTags.setBlogsId(id);
            blogTags.setTagsId(tagId);
            blogTagsMapper.insert(blogTags);
        }


        return Result.success(null, "新增博客成功");
//        blog.setTotal(); 字数
//        blog.setTime(); // 阅读时长
//        blog.setDescription(w);
    }

    @Override
    public Result<Object> selectPage(Integer index, Integer size, String keyWords) {
//        index = (index - 1) * size;
        if (keyWords.equals("")) {    // 如果不是搜索查询
//            wrapper.like("name", keyWords);
            keyWords = null;
        }
        List<AdminBlogVo> list = blogMapper.selectAdminBlogVo((index - 1) * size, size, keyWords);
        List<AdminBlogVo> adminBlogVos = blogMapper.selectAdminBlogVo(0, 0, keyWords);
        int total = adminBlogVos.size();
//        Integer integer = blogMapper.selectCount(null);
        HashMap<String, Object> map = new HashMap<>();
        map.put("list", list);
        map.put("total", total);
        return Result.success(map, "获取后台博客分页数据成功");
    }

    @Override
    public Result<Object> delete(Integer id) {
        int i = blogMapper.deleteById(id);
        if (i > 0) {
            return Result.success(null, "删除博客成功");
        }
        return Result.error(null, "删除博客失败");

    }

    @Override
    public Result<Object> selectBlogById(Integer id) {   // 用户编辑博客的数据回显
        Blog blog = blogMapper.selectById(id);
        EditBlogVo editBlogVo = new EditBlogVo();
        editBlogVo.setId(blog.getId());
        editBlogVo.setDescription(blog.getDescription());
        editBlogVo.setTitle(blog.getTitle());
        editBlogVo.setTypeId(blog.getTypeId());
        editBlogVo.setContent(blog.getContent());
        editBlogVo.setFirstPicture(blog.getFirstPicture());
        ArrayList<Integer> list = new ArrayList<>();
        log.info("{}",blog.getFirstPicture());
        // 查出博客对应的所有标签id
        List<BlogTags> blogTagsList = blogTagsMapper.selectList(new QueryWrapper<BlogTags>().eq("blogs_id", blog.getId()));
        for (BlogTags blogTags : blogTagsList) {
            list.add(blogTags.getTagsId());
        }
        editBlogVo.setTagsId(list);
//        editBlogVo.setTitle();
        return Result.success(editBlogVo, "根据id获取博客数据成功！");
    }

    @Override
    public Result<Object> deleteBatch(List<Integer> ids) {
        if (ids.size() > 0) {
            int i = blogMapper.deleteBatchIds(ids);
            if (i > 0) {
                return Result.success(null, "批量删除成功");
            }
        }


        return Result.error(null, "删除失败");
    }

    @Override
    public Result<Object> updateBlogPlatform(UpdateBlogParams updateBlogParams) {

        String content = updateBlogParams.getContent();
        String description = updateBlogParams.getDescription();
        Integer id = updateBlogParams.getId();
        List<Integer> tagIds = updateBlogParams.getTagIds();
        String title = updateBlogParams.getTitle();
        Integer typeId = updateBlogParams.getTypeId();
        Integer userId = updateBlogParams.getUserId();
        boolean flag = false;
//         健壮性校验
        List<Blog> blogList = blogMapper.selectList(new QueryWrapper<Blog>().eq("user_id", userId));
        for (Blog blog : blogList) {
            Integer id1 = blog.getId();
            if (id1.equals(id)) {
                flag = true;
            }
        }
        if (!flag) {
            return Result.error(null, "数据不合法，修改的不是此用户的ID");
        }
        if (StringUtils.isEmpty(content) ||
                StringUtils.isEmpty(description) ||
                StringUtils.isEmpty(id) ||
                StringUtils.isEmpty(tagIds) ||
                StringUtils.isEmpty(title) ||
                StringUtils.isEmpty(typeId)
        ) return Result.error(null, "修改博客数据不合法");
        Blog blog = new Blog();
        blog.setContent(content);
        blog.setDescription(description);
        blog.setTitle(title);
        blog.setTypeId(typeId);
        blog.setId(id);
        blog.setUserId(userId);
        blog.setUpdateTime(System.currentTimeMillis());
        blogTagsMapper.delete(new QueryWrapper<BlogTags>().eq("blogs_id", id)); // 先删除中间表的数据 ，
        for (Integer tagId : tagIds) {  // 循环插入
            BlogTags blogTags = new BlogTags();
            blogTags.setTagsId(tagId);
            blogTags.setBlogsId(id);
            blogTagsMapper.insert(blogTags);
        }

        int i = blogMapper.updateById(blog);
        if (i > 0) {
            return Result.success(null, "博客修改成功！");
        }
        return Result.error(null, "博客修改失败");
    }

//    @Override
//    public Result<Object> selectPage(Integer index, Integer size) {
//
//
//    }
}
